<?php
namespace app\index\model;

use app\common\model\RemoteModel;
use think\Model;

class Retention extends RemoteModel
{

    protected $connection = 'mysql://root:JB6MUn64xICo@rm-bp1h205f36fv8pecto.mysql.rds.aliyuncs.com:3306/dragon#utf8';

    /**
     * 初始化
     *
     * @return   void
     */
    protected function initialize()
    {
        parent::initialize();
    }

    /**
     * 列表(主键列表，条件数组，闭包查询)
     *
     * @param    array $param 查询条件
     * @return   void
     */
    public function doList($param = null)
    {

        //try {

            //查询数据
            $result = self::all($param);
            $rows   = [];

            foreach ($result as $data) {
                $item = $data->getData();

                //付费率
                //
                if (0 == $item['DAU']) {
                    $item['payrate'] = 0;
                } else {
                    $item['payrate'] = $item['DPU'] / $item['DAU'];
                }

                //活跃用户平均收入
                //
                if (0 == $item['DAU']) {
                    $item['ARPU'] = 0;
                } else {
                    $item['ARPU'] = $item['DPM'] / $item['DAU'];
                }

                //付费用户平均收入
                //
                if (0 == $item['DPU']) {
                    $item['ARPPU'] = 0;
                } else {
                    $item['ARPPU'] = $item['DPM'] / $item['DPU'];
                }

                array_push($rows, $item);
            }

            //返回结果
            $res = array();

            $total = count($rows);

            if ($total > 0) {
                $res['rows']  = $rows;
                $res['total'] = $total;
            } else {
                $res['total'] = 0;
                $res['rows']  = array();
            }

            //请求类型返回
            return ($res);

        //} catch (\Exception $e) {
        //    throw new \think\Exception('异常消息:' . $e->getMessage());
        //}
    }

    /**
     * 返回数据表主键ID最大值
     *
     * @return int 当前id最大值
     */
    public function getRecentDate()
    {
        try {
            // 使用闭包查询
            $record = self::get(function ($query) {
                $query->order('date desc')->limit(1);
            });

            return $record ? $record->date : null;

        } catch (\Exception $e) {
            throw new \think\Exception('abnormal:' . $e->getMessage());
        }
    }
}
